<?php
/*
Plugin Name: Wordpress Without Borders
Plugin URI: http://bravenewcode.com
Description: Performs dynamic language translation for posts, comments, tags, categories and titles
Author: Duane Storey & Dale Mugford
Version: 1.0 alpha
Author URI: http://duanestorey.com
*/

// change these to the language you typically write in
// it has to be an identifer that's part of the bnc_lang_names array below
$bnc_source_language = 'en';

// *************************************************************
// don't edit anyting below here or horrible things might happen
$bnc_posts = array();
$bnc_posts['c'] = array();
$bnc_posts['h'] = array();
$bnc_posts['t'] = array();
$bnc_posts['k'] = array();
$bnc_posts['i'] = array();
$bnc_posts['e'] = array();
$bnc_posts['a'] = array();

$bnc_lang = 'en';

$bnc_lang_names = array();
$bnc_lang_names['en'] = 'English';
$bnc_lang_names['de'] = 'German';
$bnc_lang_names['zh'] = 'Chinese';
$bnc_lang_names['zh-cn'] = 'Chinese Simplified';
$bnc_lang_names['zh-tw'] = 'Chinese Traditional';
$bnc_lang_names['fr'] = 'French';
$bnc_lang_names['es'] = 'Spanish';
$bnc_lang_names['ru'] = 'Russian';
$bnc_lang_names['nl'] = 'Dutch';
$bnc_lang_names['ar'] = 'Arabic';
$bnc_lang_names['el'] = 'Greek';
$bnc_lang_names['it'] = 'Italian';
$bnc_lang_names['ja'] = 'Japanese';
$bnc_lang_names['ko'] = 'Korean';
$bnc_lang_names['pt-pt'] = 'Portuguese';

add_action('wp_head', 'bnc_lang_header');
add_action('wp_footer', 'bnc_lang_footer');
//add_filter('the_title', 'bnc_lang_title_filter');
add_filter('the_tags', 'bnc_lang_tag_filter');
add_filter('the_category', 'bnc_lang_category_filter');
//add_filter('the_content', 'bnc_lang_content_filter');
//add_filter('wp_list_categories', 'bnc_lang_category_filter');
//add_filter('comment_text', 'bnc_lang_comment_filter');
//add_filter('the_excerpt',  'bnc_lang_excerpt_filter');

$original_count = 0;
$translated_count = 0;

function bnc_is_admin() {
	return (strpos($_SERVER['REQUEST_URI'], '/wp-admin') !== false);
}

function bnc_is_translating() {
	global $bnc_lang;
	global $bnc_lang_names;
	global $bnc_source_language;

	$translating = 0;
	if (!($bnc_lang == $bnc_source_language)) {
		$translating = 1;
	}

	if (!isset($bnc_lang_names[$bnc_lang])) {
		$translating = 0;
	}

	return $translating;
}

function bnc_lang_header() {
	global $bnc_lang;
	global $bnc_lang_names;
	global $bnc_source_language;

	if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
		$vars = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);

		if (isset($vars[0])) {
			$bnc_lang = $vars[0];	

			if (!isset($bnc_lang_names[$bnc_lang])) {
				if (strlen($bnc_lang) > 2) {
					$bnc_lang = substr($bnc_lang, 0, 2);
					if (!isset($bnc_lang_names[$bnc_lang])) {
						$bnc_lang = $bnc_source_language;
					}
				}
			}
		}
	}
	
	if (bnc_is_admin()) {
		return;
	}

  $dir = preg_split("/wp-content/", __FILE__, $result);
  $dir = preg_split("#/noborders.php#", $dir[1], $result);
  $dirname = get_bloginfo('url') . '/wp-content' . $dir[0] . '/';
  
	echo('<script type="text/javascript" src="http://www.google.com/jsapi"></script>');	
	echo('<script type="text/javascript" src="' . $dirname . 'js/prototype-1.5.0-packer.js"></script>');
}

function bnc_lang_title_filter($title) {
	if (bnc_is_admin() || !bnc_is_translating()) {
		return $title;
	}

	global $post;
	global $bnc_posts;
	
	if (!isset($bnc_posts['h'][$post->ID])) {
		$bnc_posts['h'][$post->ID] = 0;
	}

	return bnc_split_content($title, 'bnc_lang_h', $bnc_posts['h'][$post->ID], $post->ID);
}

function bnc_the_title() {
	$content = get_the_title();
	echo bnc_lang_title_filter($content);
}

function bnc_lang_excerpt_filter($excerpt) {
	if (bnc_is_admin() || !bnc_is_translating()) {
		return $cat;
	}

	global $post;
	global $bnc_posts;

	if (!isset($bnc_posts['e'][$post->ID])) {
		$bnc_posts['e'][$post->ID] = 0;
	}

	return bnc_split_content($excerpt, 'bnc_lang_e', $bnc_posts['e'][$post->ID], $post->ID);
}

function bnc_the_excerpt() {
	echo bnc_lang_excerpt_filter(get_the_excerpt());
}

function bnc_the_content($more_link_text = '(more...)', $stripteaser = 0, $more_file = '') {
        $content = get_the_content($more_link_text, $stripteaser, $more_file);
        $content = apply_filters('the_content', $content);
        $content = str_replace(']]>', ']]&gt;', $content);
	echo bnc_lang_content_filter($content);
}

function bnc_lang_comment_filter($comment) {
	if (bnc_is_admin()) {
		return $comment;
	}

	global $post;
	global $bnc_posts;

	if (!isset($bnc_posts['i'][$post->ID])) {
		$bnc_posts['i'][$post->ID] = 0;
	}

	//$comment = $str = str_replace("\r\n", " ", $comment);

	return bnc_split_content($comment, 'bnc_lang_i', $bnc_posts['i'][$post->ID], $post->ID);
}

function bnc_comment_text() {
	echo bnc_lang_comment_filter(apply_filters('comment_text', get_comment_text()));
}

function bnc_translate_callback($content) {
  global $bnc_posts;  
  
	if (!isset($bnc_posts['a'][0])) {
		$bnc_posts['a'][0] = 0;
	}
  	
  echo bnc_split_content($content, 'bnc_lang_a', $bnc_posts['a'][0], 0);
}

function bnc_translate_start() {
  ob_start();
}

function bnc_translate_stop() {
  $c = ob_get_contents();
  ob_end_clean();
  echo bnc_translate_callback($c);
}

function bnc_lang_tag_filter($tag) {
	if (bnc_is_admin() || !bnc_is_translating()) {
		return $tag;
	}

	global $post;
	global $bnc_posts;

	if (!isset($bnc_posts['t'][$post->ID])) {
		$bnc_posts['t'][$post->ID] = 0;
	}

	return bnc_split_content($tag, 'bnc_lang_t', $bnc_posts['t'][$post->ID], $post->ID);
}

function bnc_lang_category_filter($cat) {
	if (bnc_is_admin() || !bnc_is_translating()) {
		return $cat;
	}

	global $post;
	global $bnc_posts;

	if (!isset($bnc_posts['k'][$post->ID])) {
		$bnc_posts['k'][$post->ID] = 0;
	}

	return bnc_split_content($cat, 'bnc_lang_k', $bnc_posts['k'][$post->ID], $post->ID);

}

function bnc_split_content($content, $prefix, &$incr, $id) {	
	global $original_count;
	global $translated_count;

        $r = '<span class="bnc_original" id="bnc_original_' . $original_count . '">' . $content . '</span><span id="bnc_trans_' . $translated_count . '" style="display: none;">';
	$original_count++;
	$translated_count++;

        $len = strlen($content);
        $doit = true;
        $isopen = false;
	$rcount = 0;
        for ($i = 0 ; $i < $len; $i++) {
		if ($content[$i] == "\r" || $content[$i] == "\n") {
			$rcount++;
		} else $rcount = 0;

            if ($isopen && ($content[$i] == '<' || $content[$i] == "\r" || $content[$i] == "\n")) {
                $r = $r . '</span>';
                $isopen = false;
            }

            if ($doit && $content[$i] == '<') {
                $doit = false;
            }

            if ($doit && $content[$i] != "\r" && $content[$i] != "\n") {
                $r = $r . '<span id="' . $prefix . '_' . $incr . '_' . $id . '">';
		$incr++;

                $isopen = true;
                $doit = false;
            }

            $r .= $content[$i];

            if (!$isopen && $content[$i] == '>') {
                $doit = true;
            }

/*
		if (!$isopen && ($content[$i] == "\r" || $content[$i] == "\n") && $rcount % 2 == 0) {
			$doit = true;
		}
*/
        }

        if ($isopen) {
            $r = $r . '</span>';
        }

	return $r . '</span>';
}

function bnc_lang_content_filter($content) {
	if (bnc_is_admin() || !bnc_is_translating()) {
		return $content;
	}

        global $post;
        global $bnc_posts;

	if (!isset($bnc_posts['c'][$post->ID])) {
		$bnc_posts['c'][$post->ID] = 0;
	}

	return bnc_split_content($content, 'bnc_lang_c', $bnc_posts['c'][$post->ID], $post->ID);
}


function bnc_lang_footer() { 
	if (bnc_is_admin()) {
		return;
	}

	global $bnc_posts; global $bnc_source_language; global $translated_count; global $bnc_lang_names; global $bnc_lang; global $original_count; $types = array('h','c','e','t','k','i','a'); ?>

	<div style="position: fixed; top: 0px; width: 100%; left: 0px; text-align: center; border: 1px solid; padding: 2px; background: #444; color: #fff; border: 0px; font-family: arial; font-size: 11pt; z-index: 10; opacity: 0.6; display: none;" id="bnc_translating">
		<span id="bnc_trans_state1"><a href="#nowhere" onclick="bnc_show_translated()" style="color: #fff; hover: #aaa;"><span id="bnc_translate_info">Display As <?php echo $bnc_lang_names[$bnc_lang]; ?></span></span></a>
		<span id="bnc_trans_state2" style="display: none;"><a href="#nowhere" onclick="bnc_show_translated()" style="color: #fff; hover: #aaa;"><span id="bnc_translate_info2">Show Original</span></span></a>
	</div

	<script type="text/javascript">
		google.load("language", "1");

		var curstate = 0;
		var hasloaded = 0;

		function bnc_show_translated() {
			if (hasloaded == 0) {
				bnc_lang_callback();
				hasloaded = 1;
			}

			for (i = 0; i < <?php echo $original_count; ?>; i++) {
				var elem = $("bnc_original_" + i);
				if (elem) {
					if (curstate) {
						elem.show();
					} else {
						elem.hide();
					}	
				}
			}

			for (i = 0; i < <?php echo $translated_count; ?>; i++) {
				var elem = $("bnc_trans_" + i);
				if (elem) {
					if (curstate) {
						elem.hide();
					} else {
						elem.show();
					}
				}
			}

			if (curstate) {
				$("bnc_trans_state1").show();
				$("bnc_trans_state2").hide();
				curstate = 0;
			} else {
				$("bnc_trans_state1").hide();
				$("bnc_trans_state2").show();
				curstate = 1;
			}
		}

                function bnc_detect_div(div_id) {
                        var text = document.getElementById(div_id);
                        if (text) {
                                text = text.innerHTML;
				if (text.length > 0) {
                                google.language.detect(text, 
                                        function(result) {
						if (!result.error) {
                                        		if (result.language != "<?php echo $bnc_lang; ?>") {
								if (result.confidence > 0.25) {
									$("bnc_translating").show();
									bnc_xlate_div(result.language, div_id, "en");
								}
							}
						}
          } );
				}
			}
  }


  function bnc_xlate_div(src_lang,div_id,o_lang) {
			var text = document.getElementById(div_id);
        if (text) {
          text = text.innerHTML;
          google.language.translate(text, src_lang, o_lang,
					function(result) { 
						var translated = document.getElementById(div_id); if (result.translation) { translated.innerHTML = result.translation; } }); 
				}
		}

		function bnc_lang_callback() {

			<?php foreach ($types as $t) { ?>
				<?php foreach ($bnc_posts[$t] as $p => $count) { ?>
					<?php for ($i = 0; $i < $count; $i++) { ?>
							bnc_xlate_div("<?php echo $bnc_source_language; ?>", "<?php echo 'bnc_lang_' . $t . '_' . $i . '_' . $p; ?>", "<?php echo $bnc_lang; ?>");
					<?php } ?>
				<?php } ?>
			<?php } ?>
		}

		function bnc_startup() {
			bnc_xlate_div("en", "bnc_translate_info", "<?php echo $bnc_lang; ?>");
			bnc_xlate_div("en", "bnc_translate_info2", "<?php echo $bnc_lang; ?>");

			<?php if (bnc_is_translating()) echo('$("bnc_translating").show();'); ?>
			<?php foreach ($bnc_posts['i'] as $p => $count) { ?>
                        	<?php for ($i = 0; $i < $count; $i++) {
                                	echo('bnc_detect_div("bnc_lang_i_' . $i . '_' . $p . '");');
                                } ?>
                        <?php } ?>
		}

		google.setOnLoadCallback(bnc_startup);
	</script>
<?php } ?>
